package Visualisation;

import java.awt.Color;
import java.awt.Window;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.StringTokenizer;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Visual extends Thread {
	private int newPosition;
	public static void main(String[] args) throws InterruptedException {
		new Visual();
	}

	public Visual() throws InterruptedException{
		//final int ARRAY=array;
		DataInputStream dis = null;
		int[] carArray = new int[5000];
		int position;
		Car car = null;

		JPanel canvas=new JPanel();

		JFrame frame =new JFrame();
		frame.setVisible(true);
		frame.setSize(1200, 600);

		
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setLocationRelativeTo(null);
		Road road = new Road();

		frame.add(road);
		road.drawing();
		frame.add(canvas);





		try {

			File f = new File("out.dat");
			FileInputStream fis = new FileInputStream(f);
			BufferedInputStream bis = new BufferedInputStream(fis);
			dis = new DataInputStream(bis);
			//we will read in and load the frequency table with values from the text file

			String str;

			while ((str = dis.readLine()) != null) {
				StringTokenizer st = new StringTokenizer(str, "\t");                   

				for(int i=0; i<carArray.length; i++){
					carArray[i]=0;

				}
				System.out.println("\n");
				while(st.hasMoreTokens()){

					String mystring = st.nextToken().replaceAll("-", "0");
					position=Integer.valueOf(mystring).intValue();

					carArray[position]=position;
				}

				for(int i=0; i<carArray.length;i++){
					if(carArray[i]>0){
						car =new Car(canvas);
						car.draw(carArray[i]*16);
					}
					else{
						if(car!=null)
							car.remove(carArray[i]);
					}
				
				}

				sleep(100);
	if(car!=null){			
canvas.repaint();
	}
								

			} 
		} catch (IOException e) {
			System.out.println("Uh oh, got an IOException error: " + e.getMessage());
		} finally {
			// if the file opened okay, make sure we close it
			if (dis != null) {
				try {
					dis.close();
				} catch (IOException ioe) {
					System.out.println("IOException error trying to close the file: " );
				}
			} // end if
		} // end finally
		


	}

}
